package com.everflourish.yeah100.act.markingsystem;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.entity.clazz.ClassManage;
import com.everflourish.yeah100.entity.clazz.ClassManagerModel;
import com.everflourish.yeah100.http.ClassManageRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lapism.searchview.SearchView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/5.
 * 时间：2016/7/5
 */
public class ClassExamActivity extends BaseActivity {

    private Toolbar mToolBar;
    private RecyclerView mClazzList;
    private ArrayList<ClassManagerModel> mList;
    private ArrayList<ClassManagerModel> mHaveChecklist;
    private ArrayList<ClassManagerModel> mBackupList;
    private ClassExamAdapter mAdapter;
    private ClassManageRequest mRequest;
    private LoadDialog mLoadDialog;
    private SearchView mSearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_share);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mRequest = ClassManageRequest.getInstance();
        mList = new ArrayList<ClassManagerModel>();
        mHaveChecklist = (ArrayList<ClassManagerModel>) getIntent()
                .getSerializableExtra(IntentUtil.CLASS_LIST);
        if (mHaveChecklist != null) {
            mList.addAll(mHaveChecklist);
            mBackupList = CommonUtil.deepCopy(mList);
        }
        mAdapter = new ClassExamAdapter(mContext, ClassExamActivity.this, mBackupList);
    }

    private void initView() {
        mToolBar = (Toolbar) findViewById(R.id.teacher_toolbar);
        mClazzList = (RecyclerView) findViewById(R.id.teacher_share_list);
        mSearchView = (SearchView) findViewById(R.id.teacher_share_searchView);
        mSearchView.setVisibility(View.GONE);
    }

    private void configView() {
        mToolBar.setTitle("参考班级");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishMenuActivity();
            }
        });
        mClazzList.setLayoutManager(new LinearLayoutManager(mContext));
        mClazzList.setAdapter(mAdapter);
        classListRequest();
    }

    /**
     * 参考班级列表请求
     */
    private void classListRequest() {
        mLoadDialog = LoadDialog.show(mContext, null, "加载中...", mQueue);
        JsonObjectRequest request = mRequest.classListRequest(
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getClassListListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取班级列表失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 参考班级列表监听
     *
     * @param response
     */
    private void getClassListListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.CLASSES);
                Gson gson = new Gson();
                Type type = new TypeToken<List<ClassManage>>() {
                }.getType();
                List<ClassManage> classesList = gson.fromJson(
                        jsonArray.toString(), type);
                setClassList(classesList);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.class_06071_000012E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.class_060799_999999E);
            } else {
                MyToast.showShort(mContext, "获取班级列表失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "获取班级列表失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 设置mList 将List<ExaminationClass>转换成ArrayList<Map<String,Object>>()
     *
     * @param classesList
     */
    private void setClassList(List<ClassManage> classesList) {
        List<ClassManagerModel> classManagerModels = new ArrayList<ClassManagerModel>();
        for (ClassManage c : classesList) {
            if (!hasClass(c)) {
                ClassManagerModel classManagerModel = new ClassManagerModel();
                classManagerModel.setClassManage(c);
                classManagerModel.setIsCheck(false);
                classManagerModels.add(classManagerModel);
            }
        }
        mBackupList.addAll(0, classManagerModels);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 判断列表中是否已经存在该班级
     *
     * @param clazz 要判断的班级
     * @return
     */
    private boolean hasClass(ClassManage clazz) {
        boolean hasClass = false;
        for (ClassManagerModel model : mBackupList) {
            ClassManage tempClazz = model.getClassManage();
            if (tempClazz.getRosterClassId() == null) {
                tempClazz.setRosterClassId(tempClazz.getId());
            }
            if (clazz.getId().equals(tempClazz.getRosterClassId())) {// 判断id
                // 如果id相同，证明列表中已经有该班级
                hasClass = true;
                break;
            }
        }
        return hasClass;
    }

    private void finishMenuActivity() {
        Intent intent = ClassExamActivity.this.getIntent();
        intent.putExtra(IntentUtil.CLASS_LIST, mBackupList);
        ClassExamActivity.this.setResult(RESULT_OK, intent);
        ClassExamActivity.this.finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}